package org.xtframe.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.xtframe.bean.SystemConfig;
import org.xtframe.common.ActiveUserListener;
import org.xtframe.common.EncryptCount;
import org.xtframe.entity.ServerData;
import org.xtframe.entity.UserData;
import org.xtframe.service.AjaxDataHandler;
import org.xtframe.util.CommonUtil;
import org.xtframe.util.ContextUtil;

@Service
@Scope("prototype")
public class LoginDataHandler implements AjaxDataHandler {
	
	private final Log logger = LogFactory.getLog(getClass());

	public Map<String, Object> execute(String strData) {
		Map<String, Object> map = new HashMap<String, Object>();
		
		try {
			HttpSession session = ServletActionContext.getRequest().getSession();
			ServerData serverData = ContextUtil.getServerData();
			
			JSONObject objJson = JSONObject.fromObject(strData);
			JSONArray arrNamePwdRand = objJson.optJSONArray("arrNamePwdRand");
			ArrayList<String> listNamePwdRand = new ArrayList<String>();
			if(arrNamePwdRand != null) listNamePwdRand = CommonUtil.JSONArrayToArrayList_String(arrNamePwdRand);
			
			if(listNamePwdRand.size() >= 3){
				String rand = listNamePwdRand.get(2).toLowerCase();
				String randcode = session.getAttribute("loginRand").toString().toLowerCase();
				session.removeAttribute("loginRand");
				if(!rand.equals(randcode)){
					map.put(STATUS, false);
					map.put(RAND, false);
				} else {
					UserData ud = new UserData(serverData);
					if(ud.init(listNamePwdRand.get(0), EncryptCount.encryptMD5(listNamePwdRand.get(1)))) {
						session.removeAttribute(SystemConfig.LOGIN_USER);
						ActiveUserListener.SameUserOut(ud.getUser().getUserId());
						
						session.setAttribute(SystemConfig.LOGIN_USER, ud);
						map.put(STATUS, true);
					} else {
						map.put(STATUS, false);
					}
				}
			} else {
				map.put(STATUS, false);
			}
		} catch (Exception e) {
			logger.error(e.toString());
			map.clear();
			map.put(STATUS, false);
		}
		
		return map;
	}

}
